<script setup lang="ts">
import { BoundingBox, LedScreenCanvas, Matrix, Polygon, Rectangle, Shape } from "led-screen-canvas";
import { ref } from "vue";
import { ShapeType } from "led-screen-canvas/dist/led-screen-canvas/shapes";
import { LedScreenController } from "led-screen-canvas/dist/led-screen-canvas/controller";

const canvasRef = ref();

// 定义圆形对象
class Circle extends Shape {
  constructor(
    public x: number,
    public y: number,
    public radius: number,
    public borderWidth: number
  ) {
    super("circle" as ShapeType);
  }

  addToController(controller: LedScreenController): void {
    controller.shapes.push(this);
  }

  clearHover(): void {
    this.hover = false;
  }

  /**
   * 实现图形绘制接口
   */
  async draw(): Promise<boolean> {
    let { ctx, theme, scale } = this.controller;
    theme = this.getActiveTheme(theme);
    let colors = theme.default;
    if (this.active) colors = theme.active;
    else if (this.hover) colors = theme.hover;
    ctx.beginPath();
    const [cx, cy] = this.controller.cvs2win(this.x, this.y);
    const radius = this.radius * scale;
    ctx.arc(cx, cy, radius, 0, 2 * Math.PI);
    ctx.fillStyle = colors.fillColor;
    ctx.strokeStyle = colors.borderColor;
    ctx.lineWidth = this.borderWidth * scale;
    ctx.fill();
    ctx.stroke();
    ctx.closePath();
    return true;
  }

  getBoundingBox(): BoundingBox {
    return BoundingBox.fromXywh(
      this.x - this.radius,
      this.y - this.radius,
      this.radius * 2,
      this.radius * 2
    );
  }

  isActive(e: MouseEvent): boolean {
    return this.active;
  }

  moveTo(x: number, y: number, start: number[], e: MouseEvent): void {
    this.x = x;
    this.y = y;
  }

  setActive(active: boolean, e: MouseEvent): void {
    this.active = active;
  }

  toHover(cvsX: number, cvsY: number): void {
    const [dx, dy] = [cvsX - this.x, cvsY - this.y];
    this.hover = dx * dx + dy * dy < this.radius * this.radius;
  }
}

const onReady = () => {
  const circle1 = new Circle(100, 100, 50, 5);
  circle1.canMove = true;
  const circle2 = new Circle(300, 100, 50, 5);
  circle2.canMove = true;
  canvasRef.value.addShapes([circle1, circle2]);
};
</script>

<template>
  <a-space direction="vertical" style="width: 100%" wrap>
    <a-space>
      <a-button type="primary" @click="canvasRef.start()">开始渲染</a-button>
      <a-button type="primary" status="danger" @click="canvasRef.stop()"
        >暂停渲染(避免多个画布导致浏览器卡顿)</a-button
      >
      <a-button @click="canvasRef.resetZoom()">缩放到最适合的大小</a-button>
      <a-button @click="canvasRef.zoom2RealSize()">缩放到原始尺寸</a-button>
    </a-space>
    <led-screen-canvas
      style="height: 400px; background-color: #dddddd"
      ref="canvasRef"
      @on-ready="onReady"
      @on-click="shape => (shape.active = !shape.active)"
      @on-shape-move-start="shape => shape.setZIndexTop()"
    />
  </a-space>
</template>

<style scoped lang="less"></style>
